# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)
# _GATEWAY = 'http://opsweb.koolyun.cn/mobilepay/index.do'
_GATEWAY = 'https://mobile.openepay.com/mobilepay/index.do'
APP_CONF = {
    '108510160818003': {
        'API_KEY': '1234567890'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    '''  生成签名 '''
    s = ''
    for k in parameter.keys():
        if parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info(u'origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(param, key):
    parameter_dict = OrderedDict((
        ('merchantId', param['merchantId']),
        ('version', param['version']),
        ('language', param.get('language', '')),
        ('signType', param['signType']),
        ('payType', param.get('payType', '')),
        ('issuerId', param.get('issuerId', '')),
        ('mchtOrderId', param['mchtOrderId']),
        ('orderNo', param['orderNo']),
        ('orderDatetime', param['orderDatetime']),
        ('orderAmount', param['orderAmount']),
        ('payDatetime', param['payDatetime']),
        ('ext1', param.get('ext1', '')),
        ('ext2', param.get('ext2', '')),
        ('payResult', param['payResult']),
    ))
    calculated_sign = generate_sign(parameter_dict, _KEY)
    sign = param['signMsg']
    if sign != calculated_sign:
        _LOGGER.info("openepay sign: %s, calculated sign: %", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % param)


def build_form(params):
    html = u"<head><title>loading...</title></head><form id='openepaysubmit' name='openepaysubmit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['openepaysubmit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('inputCharset', 1),
        ('receiveUrl', '{}/pay/api/{}/openepay/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH)),
        ('version', 'v1.0'),
        ('language', 1),
        ('signType', 0),
        ('merchantId', app_id),
        ('orderNo', pay.id),
        ('orderAmount', int(pay_amount * 100)),
        ('orderCurrency', 156),
        ('orderDatetime', local_now().strftime('%Y%m%d%H%M%S')),
        ('productName', u'商品'),
        ('payType', 0),
    ))
    parameter_dict['signMsg'] = generate_sign(parameter_dict, api_key)
    charge_info = build_form(parameter_dict)
    charge_resp.update({
        'charge_info': charge_info
    })
    return charge_resp


def check_notify_sign(request):
    data = request.POST
    _LOGGER.info("openepay notify data: %s", data)
    app_id = data['merchantId']
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('openepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['payResult'])
    mch_id = pay.mch_id
    trade_no = data['mchtOrderId']
    total_fee = float(data['orderAmount']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('openepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
